package com.yunjinsuke.recharge.controller;

import com.alibaba.fastjson.JSONObject;
import com.yunjinsuke.recharge.common.ObjectId;
import com.yunjinsuke.recharge.controller.api.APIEnum;
import com.yunjinsuke.recharge.controller.api.ApiResponse;
import com.yunjinsuke.recharge.entity.RechargeOrder;
import com.yunjinsuke.recharge.redis.RedisKeyUtil;
import com.yunjinsuke.recharge.redis.RedisUtil;
import com.yunjinsuke.recharge.thread.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 充值
 */
@RestController
@RequestMapping("recharge")
@Slf4j
public class RechargeController {

    /**
     * 查询时间（毫秒）
     */
    public static final int QUERY_TIME_10_SECOND = 10 * 1000;

    private final RedisUtil redisUtil;

    private final AsyncService asyncService;

    public RechargeController(RedisUtil redisUtil, AsyncService asyncService) {
        this.redisUtil = redisUtil;
        this.asyncService = asyncService;
    }

    /**
     * 创建充值订单
     *
     * @param body 充值信息
     * @return 充值订单号
     */
    @PostMapping("createOrder")
    public ApiResponse recharge(@RequestBody JSONObject body) {
        // 访问token
        String accessToken = body.getString("accessToken");
        // 手机号
        String mobile = body.getString("mobile");
        // 金额
        Integer amount = body.getInteger("amount");

        // 验证token信息
        if (redisUtil.hasKey(RedisKeyUtil.accessTokenKey(accessToken))) {
            String orderNumber = ObjectId.getId();
            // 订单查询号
            String queryOrderNumber = String.format("%s:%s", orderNumber, System.currentTimeMillis());
            redisUtil.set(RedisKeyUtil.queryOrderKey(queryOrderNumber), RechargeOrder.WAITING);

            // 充值处理
            String mchId = (String) redisUtil.get(RedisKeyUtil.accessTokenKey(accessToken));
            asyncService.rechargeExecuteAsync(mchId, orderNumber, queryOrderNumber, mobile, amount);
            return new ApiResponse(new JSONObject() {{
                put("orderNumber", orderNumber);
                put("queryOrderNumber", queryOrderNumber);
            }});
        } else {
            return new ApiResponse(APIEnum.INVALID_REQUEST, "AccessToken失效");
        }
    }

    /**
     * 查询充值信息
     *
     * @param queryOrderNumber 查询订单号
     * @return 充值信息
     */
    @GetMapping("info")
    public ApiResponse recharge(@RequestParam("queryOrderNumber") String queryOrderNumber) {
        String[] split = queryOrderNumber.split(":");
        long orderTime = 0L;
        if (split.length == 2) {
            orderTime = Long.parseLong(split[1]);
        }
        if ((System.currentTimeMillis() - orderTime) > QUERY_TIME_10_SECOND) {
            Object rechargeStatusObj = redisUtil.get(RedisKeyUtil.queryOrderKey(queryOrderNumber));
            if (rechargeStatusObj != null) {
                return new ApiResponse(rechargeStatusObj);
            }
        }
        return new ApiResponse(APIEnum.INVALID_REQUEST, "");
    }

}
